<template>
  <el-form size="small">
  <el-form-item>
    <el-radio v-model='radioValue' :label="1">
    小时，允许的通配符[, - * /]
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="2">
    周期从
    <el-input-number v-model='cycle01' :min="0" :max="22" />
    -
    <el-input-number v-model='cycle02' :min="cycle01 ? cycle01 + 1 : 1" :max="23" />
    小时
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="3">
    从
    <el-input-number v-model='average01' :min="0" :max="22" />
    小时开始，每
    <el-input-number v-model='average02' :min="1" :max="23 - average01 || 0" />
    小时执行一次
    </el-radio>
  </el-form-item>
  <el-form-item>
    <el-radio v-model='radioValue' :label="4">
    指定
    <el-select clearable v-model="checkboxList" placeholder="可多选" multiple style="width:100%">
      <el-option v-for="item in 24" :key="item" :value="item-1">{{item-1}}</el-option>
    </el-select>
    </el-radio>
  </el-form-item>
  </el-form>
</template>

<script>
import { ref, watch, computed } from 'vue';

export default {
  name: 'crontab-hour',
  props: ['check', 'cron'],
  setup(props, { emit }) {
  const radioValue = ref(1);
  const cycle01 = ref(0);
  const cycle02 = ref(1);
  const average01 = ref(0);
  const average02 = ref(1);
  const checkboxList = ref([]);
  const checkNum = props.check;

  const cycleTotal = computed(() => {
    const start = checkNum(cycle01.value, 0, 22);
    const end = checkNum(cycle02.value, start ? start + 1 : 1, 23);
    return start + '-' + end;
  });

  const averageTotal = computed(() => {
    const start = checkNum(average01.value, 0, 22);
    const step = checkNum(average02.value, 1, 23 - start || 0);
    return start + '/' + step;
  });

  const checkboxString = computed(() => {
    const str = checkboxList.value.join();
    return str === '' ? '*' : str;
  });

  const radioChange = () => {
    switch (radioValue.value) {
    case 1:
      emit('update', 'hour', '*');
      break;
    case 2:
      emit('update', 'hour', cycleTotal.value);
      break;
    case 3:
      emit('update', 'hour', averageTotal.value);
      break;
    case 4:
      emit('update', 'hour', checkboxString.value);
      break;
    }
  };

  const cycleChange = () => {
    if (radioValue.value === 2) {
    emit('update', 'hour', cycleTotal.value);
    }
  };

  const averageChange = () => {
    if (radioValue.value === 3) {
    emit('update', 'hour', averageTotal.value);
    }
  };

  const checkboxChange = () => {
    if (radioValue.value === 4) {
    emit('update', 'hour', checkboxString.value);
    }
  };

  watch([radioValue, cycleTotal, averageTotal, checkboxString], () => {
    radioChange();
  });

  return {
    radioValue,
    cycle01,
    cycle02,
    average01,
    average02,
    checkboxList,
    checkNum,
    cycleTotal,
    averageTotal,
    checkboxString,
    radioChange,
    cycleChange,
    averageChange,
    checkboxChange
  };
  }
}
</script>
